package com.chagee.store.operation.server.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chagee.store.operation.server.entity.StoreDO;
import com.chagee.store.operation.server.entity.WorkOrderReceiverDO;
import com.chagee.store.operation.server.event.dao.StoreMapper;
import com.chagee.store.operation.server.event.dao.WorkOrderReceiverMapper;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

/**
 * @Author Jacky-zhan
 * @Version 1.0
 * @Date 2024/5/15 17:06
 * @Describe 添加查询接单人表数据进行（子公司为空）处理的定时任务，
 */

@Component
@Slf4j
public class FlushWorkOrderReceiverTask {

	@Resource
	private WorkOrderReceiverMapper workOrderReceiverMapper;

	@Resource
	private StoreMapper storeMapper;

	@XxlJob("flushWorkOrderReceiver")
	public ReturnT<String> flushWorkOrderReceiver(String param) {
		int total = 0;
		int process = 0;
		XxlJobLogger.log("query flushWorkOrderReceiver task start");
		// 查询接单人表的数据
		QueryWrapper<WorkOrderReceiverDO> childTaskWrapper = new QueryWrapper<>();
		childTaskWrapper.eq("delete_flag", 0);
		childTaskWrapper.orderByAsc("id");
		List<WorkOrderReceiverDO> workOrderReceiverDOList = workOrderReceiverMapper.selectList(childTaskWrapper);
		if (CollectionUtils.isNotEmpty(workOrderReceiverDOList)) {
			total = total + workOrderReceiverDOList.size();
			for (WorkOrderReceiverDO workOrderReceiverDO : workOrderReceiverDOList) {
				String storeCode = workOrderReceiverDO.getStoreCode();
				if (StringUtils.isNotBlank(storeCode)) {
					QueryWrapper<StoreDO> storeDOQueryWrapper = new QueryWrapper<>();
					storeDOQueryWrapper.eq("delete_flag", 0).eq("store_no", storeCode);
					StoreDO storeDO = storeMapper.selectOne(storeDOQueryWrapper);
					if (Objects.nonNull(storeDO)) {
						String companyId = storeDO.getCompanyId();
						String companyName = storeDO.getCompanyName();
						workOrderReceiverDO.setCompanyId(StringUtils.isNotBlank(companyId) ? companyId : "");
						workOrderReceiverDO.setCompanyName(StringUtils.isNotBlank(companyName) ? companyName : "");
						int i = workOrderReceiverMapper.updateById(workOrderReceiverDO);
						if (i > 0) {
							process = process + i;
						}
					}
				}
			}
		}
		XxlJobLogger.log("总数据：" + total + " 成功处理：" + process);
		return ReturnT.SUCCESS;
	}

}
